package com.example.exceldemo.controller;

import com.example.exceldemo.exception.BizException;
import com.example.exceldemo.model.ApiResult;
import com.example.exceldemo.service.ApiService;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * API控制器
 * 提供异步API调用接口
 */
@Slf4j
@RestController
@RequestMapping("/api")
public class ApiController {

    private final ApiService apiService;

    @Autowired
    public ApiController(ApiService apiService) {
        this.apiService = apiService;
    }

    /**
     * 异步调用外部API
     *
     * @param requestBody 请求体
     * @param metadata 元数据，用于描述任务
     * @return 任务ID
     */
    @PostMapping(value = "/async-call", produces = MediaType.APPLICATION_JSON_VALUE)
    public ApiResult<Map<String, Object>> callApiAsync(
            @RequestBody String requestBody,
            @RequestParam(value = "metadata", required = false) String metadata) {
        try {
            log.info("接收到异步API调用请求，元数据: {}", metadata);
            
            JSONObject jsonRequestBody = new JSONObject(requestBody);
            String taskId = apiService.callApiAsync(jsonRequestBody, metadata);
            
            Map<String, Object> resultData = new HashMap<>(2);
            resultData.put("taskId", taskId);
            resultData.put("message", "API请求已提交，请使用任务ID查询进度");
            
            return ApiResult.success("异步API调用已提交", resultData);
        } catch (Exception e) {
            log.error("异步API调用出错: {}", e.getMessage(), e);
            return ApiResult.fail(BizException.systemError("异步API调用失败: " + e.getMessage()).getCode(), e.getMessage());
        }
    }
} 